import axios from 'axios'
import qs from 'qs'
import vue from '../main'

// 超时码
const ERR_TIMEOUT = '0004'
const ERR_OK = '0000'

/**
 * @description: axios Get方式
 * @param {url, data, otherOptions}
 * @return:
 */
 export const ajaxGet = (url, data, otherOptions = {}) => {
    return new Promise((resolve) => {
      axios
        .get(url, {
          params: data,
          withCredentials: true,
          headers: {
            // token:
            //   router.name !== 'login' && getKey('token')
            //     ? getKey('token')
            //           : undefined,
              'Content-Type': "application/x-www-form-urlencoded;charset=UTF-8"
          },
          ...otherOptions,
        })
        .then((res) => {
          if (res.data.code === ERR_TIMEOUT) {
            vue.$warningMessage(res.message)
            return
          }
          if (res.data.code !== ERR_OK) {
            // console.log(res.message)
            vue.$warningMessage(res.message)
          }
  
          resolve(res)
        })
        .catch((res) => {
          console.log('服务器出错，请联系开发人员')
          resolve(res)
        })
    })
  }
  
  /**
   * @description: axios Post方式
   * @param {url,data}
   * @return:
   */
  export const ajaxPost = (url, data, isJson = false) => {
    return new Promise((resolve) => {
      axios
        .post(url,isJson ? qs.parse(data) : qs.stringify(data), {
          // withCredentials: true,
          headers: {
            // token:
            //   router.name !== 'login' && getKey('token')
            //     ? getKey('token')
            //             : undefined,
              'Content-Type': isJson ? 'application/json' : 'application/x-www-form-urlencoded;charset=UTF-8',
          },
        })
        .then((res) => {
          if (res.data.code === ERR_TIMEOUT) {
            vue.$warningNotice(res.data.message)
            return
          }
          if (res.data.code !== ERR_OK) {
            vue.$warningNotice(res.data.message)
          }
  
          resolve(res)
        })
        .catch((res) => {
          console.log('服务器出错，请联系开发人员')
          resolve(res)
        })
    })
  }
  